package com.cdz.charger.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class EmailUtil {

    // 发送邮件的方法
    public static void sendEmail(String toEmail, String subject, String body) {
        final String fromEmail = "3030232075@qq.com"; // 发送者的QQ邮箱地址
        final String emailPassword = "vtfiictudlkkdcig"; // QQ邮箱的授权码

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com"); // SMTP服务器地址
        props.put("mail.smtp.socketFactory.port", "465"); // SSL端口
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromEmail, emailPassword);
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromEmail));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
            message.setSubject(subject);
            message.setText(body);

            Transport.send(message);
            System.out.println("邮件发送成功...");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    // 主方法用于测试
    public static void main(String[] args) {
        // 调用sendEmail方法发送邮件
        sendEmail("3030232075@qq.com", "测试邮件主题", "这是一封来自zs的Java程序的测试邮件！");
    }
}